函數式API
在pytorch中,nn模組都有一個函數式的版本,存在torch.nn.functional之中,本身沒有參數的層可以換成函數式版本,像是池化和激活函數。
也就是把神經網絡寫成nn.module的子類別
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(16, 8, kernel_size=3, padding=1)
        self.fc1 = nn.Linear(8 * 8 * 8, 32)
        self.fc2 = nn.Linear(32, 2)
        
    def forward(self, x):
        out = F.max_pool2d(torch.tanh(self.conv1(x)), 2)
        out = F.max_pool2d(torch.tanh(self.conv2(out)), 2)
將最大池化和激活函數替換成函數式API
        out = out.view(-1, 8 * 8 * 8)
扁平化卷積模組的輸出
        out = torch.tanh(self.fc1(out))
        out = self.fc2(out)
        return out